package org.orbroker.callback

import java.util.logging._

/**
 * Callback for logging to the JDK logger.
 * @param logger The JDK logger
 * @param sqlLevel The log level for executed SQL statements
 * @param thresholdMillis Only log statements taking longer than threshold
 * @param ignoreWarnings Set of SQL state codes to ignore when warned
 */
class JDKLoggingCallback(logger: Logger, sqlLevel: Level, thresholdMillis: Int = 0,
    ignoreWarnings: Set[String] = Set.empty) extends ExecutionCallback with LogEmbeddedValues {
  def onSQL(id: Symbol, sql: String, parms: Seq[Any], executionTime: Int) {
    val millis = executionTime / 1000
    if (millis >= thresholdMillis) {
      val sqlWithValues = embedValues(sql.trim, parms)
      logger.log(sqlLevel,
        "Executed '{0}' taking {1} ms: {2}",
        Array(id.name, int2Integer(millis), sqlWithValues))
    }
  }


  def onSQLBatch(id: Symbol, sql: String, parms: Seq[Seq[Any]], executionTime: Int) {
    val millis = executionTime / 1000
    if (millis >= thresholdMillis) {
    logger.log(sqlLevel,
      "Executed '{0}' {1} times as batch taking {2} ms: {3}",
      Array(id.name, int2Integer(parms.size), int2Integer(millis), sql.trim))
    }
  }

  def onWarning(warning: java.sql.SQLWarning) = {
    if (!ignoreWarnings.contains(warning.getSQLState)) {
      logger.warning("[" + warning.getSQLState + "] " + warning.getMessage)
    }
  }

}
